from django.contrib.auth.hashers import make_password
from django.http.response import HttpResponse
import datetime
from firepark_admin.models import register, use_records, park_info, parking_lot

# Create your views here.
# 用户注册
def regist(request):
    if request.method=="GET":
        # 127.0.0.1:8000/info/?user_name=20&password=30
        user_name=request.GET.get('user_name')
        password=request.GET.get('password')
        today_time = str(datetime.datetime.now()).split('.')[0]
        print(today_time)
        today_time = datetime.datetime.strptime(today_time, '%Y-%m-%d %H:%M:%S')
        create_user(user_name,password,today_time)
        return HttpResponse("GET")
    elif request.method=="POST":
        user_name=request.POST['user_name']
        password=request.POST['password']
        today_time = str(datetime.datetime.now()).split('.')[0]
        print(today_time)
        today_time = datetime.datetime.strptime(today_time, '%Y-%m-%d %H:%M:%S')
        create_user(user_name,password,today_time)
        return HttpResponse("POST")

def recharge(request):
    if request.method=="POST":
        password=request.POST['password']
        user_name=request.POST['user_name']
        number=request.POST['number']
        result=user_recharge(password=password,user_name=user_name,number=number)
    elif request.method=="GET":
        password=request.GET['password']
        user_name=request.GET['user_name']
        number=request.GET['number']
        result=user_recharge(password=password,user_name=user_name,number=number)
    return HttpResponse(result)

def login(request):
    if request.method=="POST":
        password=request.POST['password']
        user_name=request.POST['user_name']
        result=user_login(password=password,user_name=user_name)
    elif request.method=="GET":
        password=request.GET['password']
        user_name=request.GET['user_name']
        result=user_login(password=password,user_name=user_name)
    return HttpResponse(result)



def user_confirm(user_name,password):
    password=make_password(password, None, 'pbkdf2_sha256')
    results=register.objects.filter(user_name__exact=user_name).values
    if results[0].get('password')==password:
        return True
    else:
        return False

def create_user(user_name,password,create_time):
    register.objects.create(password=password,user_name=user_name,balance=0,create_time=create_time,update_time=create_time,flag=True)

def user_recharge(user_name,password,number):
    results=register.objects.filter(user_name__exact=user_name).values
    if user_confirm(user_name,password):
        update_balance=results[0].get('balance')+number
        user=register.objects.filter(user_name__exact=user_name)
        user.update(balance=update_balance)
        return "充值成功"
    else:
        return '密码错误'

def user_login(user_name,password,number):
    if user_confirm(user_name,password):
        return "登录成功"
    else:
        return '密码错误'